package com.example.paimengshop;

import com.example.paimengshop.client_socket.*;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.application.Platform;
import org.json.simple.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AccountController implements Initializable{
    @FXML
    private Label timeLabel1;

    @FXML
    private Label timeLabel2;
    @FXML
    public AnchorPane myPane;

    @FXML
    public RadioButton loginBtn;

    @FXML
    public RadioButton signUpBtn;

    @FXML
    public RadioButton resetBtn;

    @FXML
    private PasswordField passwordField1;

    @FXML
    private PasswordField passwordField2;

    @FXML
    public TextField mailField;

    @FXML
    public PasswordField passwordField;

    @FXML
    public Button loginButton;

    @FXML
    public Button signUpButton;

    @FXML
    public Button resetButton;


    @FXML
    public TextField verificationCodeInput;

    @FXML
    public Button getCodeBtn;

    @FXML
    public ImageView myImgView;

    private static boolean loginSucceed = false;

    public static void setLoginSucceed(boolean loginSucceed)
    {
        AccountController.loginSucceed = loginSucceed;
    }

    public static boolean isLoginSucceed()
    {
        return loginSucceed;
    }

    public static void RegisterSucceedAlert()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("注册");
        alert.setContentText("注册成功，请前往登录");
        alert.setHeaderText("注册成功");
        alert.showAndWait();
    }

    public static void WrongVerCodeAlert_Register()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("注册");
        alert.setContentText("验证码错误，请重新输入");
        alert.setHeaderText("验证码错误");
        alert.showAndWait();
    }

    public static void AlreadyRegisteredAlert()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("注册");
        alert.setContentText("该邮箱已注册，请直接登录");
        alert.setHeaderText("邮箱已注册");
        alert.showAndWait();
    }

    public static void LoginSucceedAlert()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("登录");
        alert.setContentText("登录成功，祝您购物愉快");
        alert.setHeaderText("登陆成功");
        alert.showAndWait();

    }

    public static void NotRegisteredAlert_Login()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("登录");
        alert.setContentText("该邮箱尚未注册，请先进行注册");
        alert.setHeaderText("邮箱尚未注册");
        alert.showAndWait();
    }

    public static void WrongPasswordAlert()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("登录");
        alert.setContentText("密码错误，请重新输入");
        alert.setHeaderText("密码错误");
        alert.showAndWait();
    }

    public static void ChangeSucceedAlert()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("重置密码");
        alert.setContentText("您已成功重置了您的密码");
        alert.setHeaderText("重置密码成功");
        alert.showAndWait();
    }

    public static void NotRegisteredAlert_ChangePassword()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("重置密码");
        alert.setContentText("该邮箱尚未注册，请先进行注册");
        alert.setHeaderText("邮箱尚未注册");
        alert.showAndWait();
    }

    public static void WrongVerCodeAlert_ChangePassword()
    {
        Alert alert =new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("重置密码");
        alert.setContentText("验证码错误，请重新输入");
        alert.setHeaderText("验证码错误");
        alert.showAndWait();
    }

    public static void ShowRegisterAlert()
    {
        Platform.runLater(new Runnable()
        {
            @Override
            public void run()
            {
                String feedback = ActionControl_Receive.getRegisterFeedbackJsonObject().get("feedback").toString();
                if(feedback.equals("register succeed"))
                {
                    AccountController.RegisterSucceedAlert();
                }
                else if(feedback.equals("wrong verCode"))
                {
                    AccountController.WrongVerCodeAlert_Register();
                }
                else if(feedback.equals("already registered"))
                {
                    AccountController.AlreadyRegisteredAlert();
                }
                ActionControl_Receive.setRegisterFeedbackJsonObject(new JSONObject());
            }
        });
    }

    public static void ShowLoginAlert()
    {
        Platform.runLater(new Runnable()
        {
            @Override
            public void run()
            {
                String feedback = ActionControl_Receive.getLoginFeedbackJsonObject().get("feedback").toString();
                if(feedback.equals("login succeed"))
                {
                    AccountController.LoginSucceedAlert();

                    main.getSend().Send(ActionControl_Send.AskForRefreshingCommodityInfo());

                    main.getSend().Send(ActionControl_Send.AskForRefreshingUserInfo((Integer.parseInt(ActionControl_Receive.getLoginFeedbackJsonObject().get("id").toString()))));

                    main.getSend().Send(ActionControl_Send.AskForRefreshingOrderInfo((Integer.parseInt(ActionControl_Receive.getLoginFeedbackJsonObject().get("id").toString()))));

                    loginSucceed = true;

                    Stage oldStage = (Stage) main.getAccountController().loginBtn.getScene().getWindow();
                    oldStage.close();

                FXMLLoader fxmlLoader=new FXMLLoader(this.getClass().getResource("main.fxml"));

                Scene scene= null;
                try {
                    scene = new Scene(fxmlLoader.load(),1200,650);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                Stage newStage=new Stage();
                newStage.setTitle("派蒙的周边商铺");
                newStage.setScene(scene);

                newStage.show();



                }
                else if(feedback.equals("not registered"))
                {
                    AccountController.NotRegisteredAlert_Login();
                }
                else if(feedback.equals("wrong password"))
                {
                    AccountController.WrongPasswordAlert();
                }

                ActionControl_Receive.setLoginFeedbackJsonObject(new JSONObject());


            }
        });

    }

    public static void ShowChangePasswordAlert()
    {
        Platform.runLater(new Runnable()
        {
            @Override
            public void run()
            {
                String feedback = ActionControl_Receive.getChangePasswordFeedbackJsonObject().get("feedback").toString();
                if(feedback.equals("change succeed"))
                {
                    AccountController.ChangeSucceedAlert();




                }
                else if(feedback.equals("wrong verCode"))
                {
                    AccountController.WrongVerCodeAlert_ChangePassword();
                }
                else if(feedback.equals("not registered"))
                {
                    AccountController.NotRegisteredAlert_ChangePassword();
                }
                ActionControl_Receive.setChangePasswordFeedbackJsonObject(new JSONObject());
                //更新JavaFX的主线程的代码放在此处
            }
        });
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle)    //界面的初始化
    {
        timeLabel1.setVisible(false);
        timeLabel1.setManaged(false);

        timeLabel2.setVisible(false);
        timeLabel2.setManaged(false);

        //this.receive = socketConnect.getReceive();

//        Image img= new Image("file:src/main/resources/com/example/demo13/Image/background.jpg");
//        BackgroundImage bImg = new BackgroundImage(img,
//                BackgroundRepeat.NO_REPEAT,
//                BackgroundRepeat.NO_REPEAT,
//                BackgroundPosition.DEFAULT,
//                BackgroundSize.DEFAULT);
//        Background bGround= new Background(bImg);
//        myPane.setBackground(bGround);

        ToggleGroup group = new ToggleGroup();
        loginBtn.setToggleGroup(group);
        signUpBtn.setToggleGroup(group);
        resetBtn.setToggleGroup(group);

        loginBtn.setText("登录");
        signUpBtn.setText("注册");
        resetBtn.setText("重置密码");

//        Image loginImg = new Image("file:src/main/resources/com/example/demo13/Image/login.png");
//        loginBtn.setGraphic(new ImageView(loginImg));



        myPane.getStylesheets().add(getClass().getResource("All.css").toExternalForm());
        myPane.getStyleClass().add("default-theme");

        Image img = new Image("file:PaiMengShop/PaiMengShopClient/src/main/resources/com/example/demo13/Image/paimeng.png");
        myImgView.getStyleClass().add("imgView-basic");
        myImgView.setImage(img);

        mailField.getStyleClass().add("input-group");
        passwordField.getStyleClass().add("input-group");
        verificationCodeInput.getStyleClass().add("input-group");
        passwordField1.getStyleClass().add("input-group");
        passwordField2.getStyleClass().add("input-group");
        passwordField1.setPromptText("输入密码");
        passwordField2.setPromptText("确认密码");

        loginButton.getStyleClass().add("btn-basic");
        signUpButton.getStyleClass().add("btn-basic");
        resetButton.getStyleClass().add("btn-basic");
        getCodeBtn.getStyleClass().add("btn-basic");

        myPane.getStyleClass().add("pane-radius-large");



//        LoginHandlerClass handler1 = new LoginHandlerClass();
//        loginBtn.setOnAction(handler1);

        mailField.setPromptText("邮箱");
        passwordField.setPromptText("密码");
        verificationCodeInput.setPromptText("验证码");

        verificationCodeInput.setVisible(false);
        verificationCodeInput.setManaged(false);

        getCodeBtn.setVisible(false);
        getCodeBtn.setManaged(false);

        passwordField1.setVisible(false);
        passwordField1.setManaged(false);
        passwordField2.setVisible(false);
        passwordField2.setManaged(false);

        loginButton.setText("登录");
        signUpButton.setText("注册");
        resetButton.setText("重置");

        loginBtn.setSelected(true);
        loginButton.setVisible(true);
        loginButton.setManaged(true);
        signUpButton.setVisible(false);
        signUpButton.setManaged(false);
        resetButton.setVisible(false);
        resetButton.setManaged(false);

        signUpButton.setDisable(true);
        verificationCodeInput.setPromptText("请获取验证码");
        resetButton.setDisable(true);

        Button closeBtn = new Button();
        closeBtn.setText("关闭");
        closeBtn.getStyleClass().add("btn-basic");

        myPane.getChildren().add(closeBtn);
        closeBtn.setLayoutX(1110);
        closeBtn.setLayoutY(650);

        closeBtn.setOnAction(new EventHandler<ActionEvent>()
        {
            //返回未登录的状态
            @Override
            public void handle(ActionEvent actionEvent)
            {
                if(loginSucceed)
                {
                    Stage oldStage=(Stage) loginButton.getScene().getWindow();
                    oldStage.close();

                }
                else
                {
                    Stage oldStage=(Stage) loginButton.getScene().getWindow();

                    FXMLLoader fxmlLoader=new FXMLLoader(this.getClass().getResource("mainUnlogin.fxml"));

                    Scene scene= null;
                    try {
                        scene = new Scene(fxmlLoader.load());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    Stage newStage=new Stage();
                    newStage.setTitle("派蒙的周边商铺");
                    newStage.setScene(scene);

                    oldStage.close();
                    newStage.show();
                }
//                Stage oldStage=(Stage) loginButton.getScene().getWindow();
//
//                FXMLLoader fxmlLoader=new FXMLLoader(this.getClass().getResource("mainUnlogin.fxml"));
//
//                Scene scene= null;
//                try {
//                    scene = new Scene(fxmlLoader.load());
//                } catch (IOException e) {
//                    throw new RuntimeException(e);
//                }
//
//                Stage newStage=new Stage();
//                newStage.setTitle("派蒙的周边商铺");
//                newStage.setScene(scene);
//
//                oldStage.close();
//                newStage.show();
            }
        });
    }



    public void OnGetCodeBtnClicked()
    {
        if(mailField.getText().trim().isEmpty())
        {
            Alert alert =new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("获取验证码");
            alert.setContentText("请输入邮箱");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else if(!checkEmail(mailField.getText()))
        {
            Alert alert =new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("获取验证码");
            alert.setContentText("邮箱格式错误");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else
        {
            getCodeBtn.setText("再次发送");

            timeLabel1.setVisible(true);
            timeLabel1.setManaged(true);
            timeLabel2.setVisible(true);
            timeLabel2.setManaged(true);
            timeLabel1.setText("60");
            Timer timer = new Timer();
            //定时器执行任务
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            if (Integer.parseInt(timeLabel1.getText()) > 0) {
                                int second = Integer.parseInt(timeLabel1.getText());
                                second--;
                                timeLabel1.setText(second + "");
                            } else {
                                getCodeBtn.setText("获取验证码");
                                timeLabel1.setVisible(false);
                                timeLabel1.setManaged(false);

                                timeLabel2.setVisible(false);
                                timeLabel2.setManaged(false);

                                getCodeBtn.setDisable(false);
                            }
                        }
                    });
                }
            }, 0, 1000);

            getCodeBtn.setVisible(true);
            getCodeBtn.setDisable(true);

            String email = mailField.getText();
            String password1 = passwordField1.getText();
            String password2 = passwordField2.getText();
            if(!password1.equals(password2))
            {
                Alert alert =new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("注册");
                alert.setContentText("两次输入的密码不一致");
                alert.setHeaderText("注意");
                alert.showAndWait();
            }
            else
            {
                if(signUpBtn.isSelected()) //实现注册功能，判断邮箱是否已经注册了
                {
                    main.getSend().Send(ActionControl_Send.Register(email, password2));
                }
                else    //实现重置功能，判断邮箱是否已经注册了
                {
                    main.getSend().Send(ActionControl_Send.AskForRefreshingUserInfoByEmail(email));

                    main.getSend().Send(ActionControl_Send.ChangePassword(Data.currentUser ,email, password2));
                }
            }
        }
        signUpButton.setDisable(false);
        resetButton.setDisable(false);
        verificationCodeInput.setPromptText("请输入验证码");
    }
    public void OnLoginBtnClicked()
    {
        passwordField.setVisible(true);//可见
        passwordField.setManaged(true);//不隐藏

        verificationCodeInput.setVisible(false);
        verificationCodeInput.setManaged(false);

        getCodeBtn.setVisible(false);
        getCodeBtn.setManaged(false);

        getCodeBtn.setText("获取验证码");

        mailField.clear();
        passwordField.clear();
        verificationCodeInput.clear();
        passwordField1.clear();
        passwordField2.clear();

        loginButton.setVisible(true);
        loginButton.setManaged(true);
        signUpButton.setVisible(false);
        signUpButton.setManaged(false);
        resetButton.setVisible(false);
        resetButton.setManaged(false);

        passwordField1.setVisible(false);
        passwordField1.setManaged(false);
        passwordField2.setVisible(false);
        passwordField2.setManaged(false);

        verificationCodeInput.setPromptText("请获取验证码");
    }

    public void OnSignUpBtnClicked()
    {


        verificationCodeInput.setVisible(true);
        verificationCodeInput.setManaged(true);

        passwordField.setVisible(false);//不可见
        passwordField.setManaged(false);//真正隐藏

        getCodeBtn.setVisible(true);
        getCodeBtn.setManaged(true);

        getCodeBtn.setText("获取验证码");

        mailField.clear();
        passwordField.clear();
        verificationCodeInput.clear();
        passwordField1.clear();
        passwordField2.clear();

        loginButton.setVisible(false);
        loginButton.setManaged(false);
        signUpButton.setVisible(true);
        signUpButton.setManaged(true);
        resetButton.setVisible(false);
        resetButton.setManaged(false);

        passwordField1.setVisible(true);
        passwordField1.setManaged(true);
        passwordField2.setVisible(true);
        passwordField2.setManaged(true);

        verificationCodeInput.setPromptText("请获取验证码");
    }

    public void OnResetBtnClicked()
    {
        verificationCodeInput.setVisible(true);
        verificationCodeInput.setManaged(true);

        passwordField.setVisible(false);//不可见
        passwordField.setManaged(false);//真正隐藏

        getCodeBtn.setVisible(true);
        getCodeBtn.setManaged(true);

        getCodeBtn.setText("获取验证码");

        mailField.clear();
        passwordField.clear();
        verificationCodeInput.clear();
        passwordField1.clear();
        passwordField2.clear();

        loginButton.setVisible(false);
        loginButton.setManaged(false);
        signUpButton.setVisible(false);
        signUpButton.setManaged(false);
        resetButton.setVisible(true);
        resetButton.setManaged(true);

        passwordField1.setVisible(true);
        passwordField1.setManaged(true);
        passwordField2.setVisible(true);
        passwordField2.setManaged(true);

        verificationCodeInput.setPromptText("请获取验证码");
    }

    public static boolean checkEmail(String email) //判断邮箱是否正确
    {
        boolean flag = false;
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public void onloginButtonClicked()
    {
        //获取用户输入的账户信息
        //验证是否是已注册用户
        String email=mailField.getText();
        String password=passwordField.getText();
        main.getSend().Send(ActionControl_Send.Login(email, password));

    }

    public void onsignUpButtonClicked()
    {
        if(verificationCodeInput.getText().isEmpty())
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("注册");
            alert.setContentText("您还没有输入验证码");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else
        {
            String email = mailField.getText();
            String password1 = passwordField1.getText();
            String password2 = passwordField2.getText();
            int verCode = Integer.parseInt(verificationCodeInput.getText());

            if (!password1.equals(password2))
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("注册");
                alert.setContentText("两次输入的密码不一致");
                alert.setHeaderText("注意");
                alert.showAndWait();
            } else
            {
                main.getSend().Send(ActionControl_Send.SendVerCode_Register(email, password2, verCode));
                OnLoginBtnClicked();
                loginBtn.setSelected(true);
                mailField.setText(email);
            }
        }
    }

    public void onresetButtonClicked()
    {
        if(verificationCodeInput.getText().isEmpty())
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("重置密码");
            alert.setContentText("您还没有输入验证码");
            alert.setHeaderText("注意");
            alert.showAndWait();
        }
        else
        {
            String email = mailField.getText();
            String password1 = passwordField1.getText();
            String password2 = passwordField2.getText();
            int verCode = Integer.parseInt(verificationCodeInput.getText());

            if (!password1.equals(password2))
            {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("重置密码");
                alert.setContentText("两次输入的密码不一致");
                alert.setHeaderText("注意");
                alert.showAndWait();
            } else
            {
                main.getSend().Send(ActionControl_Send.SendVerCode_ChangePassword(email, password2, verCode));
                OnLoginBtnClicked();
                loginBtn.setSelected(true);
                mailField.setText(email);
            }
        }

    }
}